import Vue from 'vue'
import Router from 'vue-router'
import db from '@/utils/localstorage'
import request from '@/utils/request'
import { getUserRouters } from "@/api/user";

Vue.use(Router)

/* Layout */
import Layout from '@/layout'

/**
 * Note: sub-menu only appear when route children.length >= 1
 * Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
 *
 * hidden: true                   if set true, item will not show in the sidebar(default is false)
 * alwaysShow: true               if set true, will always show the root menu
 *                                if not set alwaysShow, when item has more than one children route,
 *                                it will becomes nested mode, otherwise not show the root menu
 * redirect: noRedirect           if set noRedirect will no redirect in the breadcrumb
 * name:'router-name'             the name is used by <keep-alive> (must set!!!)
 * meta : {
    roles: ['admin','editor']    control the page roles (you can set multiple roles)
    title: 'title'               the name show in sidebar and breadcrumb (recommend set)
    icon: 'svg-name'             the icon show in the sidebar
    breadcrumb: false            if set false, the item will hidden in breadcrumb(default is true)
    activeMenu: '/example/list'  if set path, the sidebar will highlight the path you set
  }
 */

/**
 * constantRoutes
 * a base page that does not have permission requirements
 * all roles can be accessed
 */
export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },

  {
    path: '/404',
    component: () => import('@/views/404'),
    hidden: true
  },

  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [{
      path: 'dashboard',
      name: 'Dashboard',
      component: () => import('@/views/dashboard/index'),
      meta: { title: 'Dashboard', icon: 'dashboard' }
    }]
  },
  {
    path: 'external-link',
    component: Layout,
    children: [
      {
        path: 'https://panjiachen.github.io/vue-element-admin-site/#/',
        meta: { title: 'External Link', icon: 'link' }
      }
    ]
  },

  // 404 page must be placed at the end !!!
  { path: '*', redirect: '/404', hidden: true }
]




const createRouter = () => new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})



let asyncRouter
// ---
const router = createRouter()

// // Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
  asyncRouter = null;
  // router.options.routes = constantRoutes
}

// export default router
// ---

// let router = new Router({
//   routes: constantRoutes
// })

const whiteList = ['/login']



// 导航守卫，渲染动态路由
router.beforeEach((to, from, next) => {
  console.log("---to.path=" + to.path)

  if (whiteList.indexOf(to.path) !== -1) {
    next()
  } else {
    let token = db.get('USER_TOKEN')
    let user = db.get('USER')
    console.log("------11-----" + user)
    let userRouter = get('USER_ROUTER')
    console.log("------12-----" + userRouter)

    if (token.length && user) {
      if (!asyncRouter) {
        if (!userRouter) {

          // request.get('').then((res) => {
          //   asyncRouter = res.data
          //   save('USER_ROUTER', asyncRouter)
          //   go(to, next)
          // })
          console.log("--userId---" + user.id)

          getUserRouters(user.id).then((response) => {
            console.log("------response="+response)

            asyncRouter = response.data
            save('USER_ROUTER', asyncRouter)
            go(to, next)
          })

        } else {
          asyncRouter = userRouter
          go(to, next)
        }
      } else {
        next()
      }
    } else {
      next('/login')
    }
  }
})


function go(to, next) {
  console.log("---go")
  asyncRouter = filterAsyncRouter(asyncRouter)

  console.log("---asyncRouter=" + JSON.stringify(asyncRouter))

  // 这一行不能少（不addRoutes，会导致404，路由不过去）
  router.addRoutes(asyncRouter, {replace: true})

  router.options.routes= []
  // router.options.routes.push(constantRoutes)

  for (let i = 0; i < constantRoutes.length; i++) {
    router.options.routes.push(constantRoutes[i])
  }

  if(asyncRouter && asyncRouter.length > 0){
    for (let i = 0; i < asyncRouter.length; i++) {
      router.options.routes.push(asyncRouter[i])
    }
  }

  next({ ...to, replace: true })
}

function save(name, data) {
  localStorage.setItem(name, JSON.stringify(data))
}

function get(name) {
  console.log("------name-----" + name)
  console.log("------localStorage.getItem(name)-----" + localStorage.getItem(name))

  try {
    return JSON.parse(localStorage.getItem(name))
  } catch (error) {
    return null
  }


}

function filterAsyncRouter(routes) {
  return routes.filter((route) => {
    let component = route.component
    if (component) {
      switch (route.component) {
        case 'Layout':
          route.component = Layout
          break
        default:
          // route.component = view(component)

          route.component = (resolve) => require(["@/views/"+component+"/index.vue"],resolve)

          console.log("---component="+component)
      }
    }else{
      delete route.component
    }



    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }else{
      delete route.children
    }

    return true
  })
}

function view(path) {
  // return require("@/views/"+path+"/index.vue")




  // return function (resolve) {
  //   import("@/views/"+path+"/index.vue").then(mod => {
  //     resolve(mod)
  //   })
  // }

}

export default router
